package chixing.day16;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class InputStream_Demo2 {
    public static void main(String[] args) {
        FileInputStream is = null;
        //1.创建读取流
        try {
            is = new FileInputStream("E:\\2025-cx\\project\\PJ\\J01\\Javase\\Temp\\hello.txt");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        //2.读数据
        byte[] bytes = null;
        try {
            bytes = new byte[is.available()];
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        int temp;
        int i = 0;
        try {
            while ((temp=is.read()) != -1){
                bytes[i++] = (byte)temp;
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {//3.关闭流
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        String str = new String(bytes);
        System.out.println(str);

    }
    public static void fun1(){
        //1.创建读取流
        FileInputStream is = null;
        try {
            is = new FileInputStream("E:\\2025-cx\\project\\PJ\\J01\\Javase\\Temp\\hello.txt");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        //2.读数据
        byte[] bytes = null; //将读取的数据（字节码）存入到byte数组中
        try {
            bytes = new byte[is.available()];//is.available() 获得要读取文件的大约字节数
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        int temp;//用一个临时变量来接收读取的数据（字节码）
        int i = 0;//byte中已有的字节数(读取的数据存放在数组的哪个位置)
        try {
            while ((temp = is.read())!= -1){//读到下一个为-1 的时候就表明读完了
                bytes[i++] = (byte) temp;//因为read()返回的数据类型是int类型，所以要强转为byte类型
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {//3.关闭流
            if (is != null) {//防止空指针异常
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        String str  = new String(bytes);
        System.out.println(str);
    }

}
